﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp.MyLinq.Misc
{
    public class TranslatingHost<T> : IOrderedQueryable<T>, IOrderedQueryable
    {
        private readonly IQueryable<T> query;

        public Type ElementType => typeof(T);

        private Expression TranslatedExpression { get; set; }

        public TranslatingHost(IQueryable<T> query, int maxTake)
        {
            this.query = query;
            var translator = new ExpressionTakeRestrainer();
            TranslatedExpression = translator.ParseAndConstrainTake(query.Expression, maxTake);
        }

        public Expression Expression => TranslatedExpression;

        // 使用 Linq to Objects
        public IQueryProvider Provider => query.Provider;

        // 实现的是 IEnumerable<T>.GetEnumerator() 
        public IEnumerator<T> GetEnumerator()
            => Provider.CreateQuery<T>(TranslatedExpression).GetEnumerator();


        // 实现的是 IEnumerable.GetEnumerator()
        IEnumerator IEnumerable.GetEnumerator()
            // 返回泛型的这一个 Enumerator
            => this.GetEnumerator();
    }
}
